package kyuuri.server;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.*;
import javax.xml.parsers.*;

public class UpdateNicoLive extends HttpServlet {
	private final String RSS_URL = "http://live.nicovideo.jp/recent/rss?sort=start&";
	private final int P_LIMIT = 100;
	private DocumentBuilder builder;
	
	@Override
	protected void doGet(HttpServletRequest req, final HttpServletResponse resp)
			throws ServletException, IOException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			builder = factory.newDocumentBuilder();

			for (int i = 0; i < P_LIMIT; i++) {
				String url = RSS_URL + "p=" + i;

				Document document = builder.parse(url);
				NodeList nodeList = document.getElementsByTagName("item");
				if (nodeList == null)
					break;
				for (int j = 0; j < nodeList.getLength(); j++) {
					Element element = (Element) nodeList.item(j);
					String guid = getTagValue(element, "guid");
					NicoLive live = new NicoLive(guid);
					String title = getTagValue(element, "title");
					live.setTitle(title);
					String value = getTagValue(element, "pubDate");
					live.setPubDate(toDate(value));
					String description = getTagValue(element, "description");
					live.setDescription(description);
					live.setCategory(getTagValue(element, "category"));
					Node node = element.getElementsByTagName("media:thumnail").item(0);
					if (node != null && node.hasAttributes()) {
						String url1 = ((Element) node).getAttribute("url");
						live.setThumnail(url1);
					}
					live.setCreator(getTagValue(element, "dc:creator"));
					live.setCommunityName(getTagValue(element, "nicolive:community_name"));
					live.setCommunityId(getTagValue(element, "nicolive:community_id"));
					live.setNumRes(Integer.parseInt(getTagValue(element, "nicolive:num_res")));
					String view = getTagValue(element, "nicolive:view");
					live.setView(Integer.parseInt(view));
					String memberOnly = getTagValue(element, "nicolive:member_only");
					if (memberOnly == "true")
						live.setMemberOnly(true);
					else
						live.setMemberOnly(false);
					live.setType(getTagValue(element, "nicolive:type"));
					live.setOwnerName(getTagValue(element, "nicolive:owner_name"));
					live.setBroadcasting(true);

//							Integer.parseInt(view));
					pm.makePersistent(live);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		pm.close();
	}
	
	private String getTagValue(Element element, String tagName) {
		NodeList nodeList = element.getElementsByTagName(tagName);
		if (nodeList.getLength() == 0)
			return null;
		if (!nodeList.item(0).hasChildNodes())
			return null;
		String value = nodeList.item(0).getFirstChild().getNodeValue();
		return value;
	}
	
	private Date toDate(String pub) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US);
		Date date = new Date();
		date = format.parse(pub);
		return date;
	}
}
